var command = {};
command.press = function (x, y, r) {
    console.log("press(" + x + "," + y + ")");
    rr = Math.sqrt(Math.random()) * r
    angle = Math.random() * 2 * Math.PI
    press(rr * Math.cos(angle) + x, rr * Math.sin(angle) + y, commonModule.random(100, 120))
    sleep(commonModule.random(1000, 1500));
};
command.pressNoDelay = function (x, y, r) {
    console.log("pressNoDelay(" + x + "," + y + ")");
    rr = Math.sqrt(Math.random()) * r
    angle = Math.random() * 2 * Math.PI
    press(rr * Math.cos(angle) + x, rr * Math.sin(angle) + y, commonModule.random(40, 50))
};
command.swipeUp = function (x, y, r) {
    // console.log("swipe(" + x + "," + y + ")");
    gesture(3000, [x, y], [x, y - r])
    sleep(commonModule.random(500, 1000));
};
command.swipeUpWithDuration = function (x, y, r, d) {
    console.log("swipeUpWithDuration(" + x + "," + y + ")");
    gesture(d, [x, y], [x, y - r])
};
command.swipeDown = function (x, y, r) {
    // console.log("swipe(" + x + "," + y + ")");
    gesture(3000, [x, y], [x, y + r])
    sleep(commonModule.random(500, 1000));
};
command.swipeDownWithDuration = function (x, y, r, d) {
    console.log("WithDuration(" + x + "," + y + ")");
    gesture(d, [x, y], [x, y + r])
};
command.gesture = function (x, y, r) {
    // console.log("gesture(" + x + "," + y + ")");
    gesture(commonModule.random(500, 1000), [x, y], [x, y - r])
    sleep(commonModule.random(500, 1000));
};
command.pressHold = function (x, y, r, t) {
    // console.log("press(" + x + "," + y + ")");
    rr = Math.sqrt(Math.random()) * r
    angle = Math.random() * 2 * Math.PI
    press(rr * Math.cos(angle) + x, rr * Math.sin(angle) + y, t)
};
command.jumpCoordinate = function (s, x, y) {
    // console.log("jumpCoordinate(" + s + "," + x + "," + y + ")");
    sleep(commonModule.random(10000, 11000));
    launchApp("万国觉醒");
    while (!commonModule.isWord()) {
        this.press(60, 650, 35);
        sleep(5000)
    }
    sleep(commonModule.random(1000, 2000));
    //点击查找地址按钮
    this.press(439, 18, 10);
    //点击输入服务器编码
    this.press(455, 140, 15);
    sleep(commonModule.random(2000, 3000));
    setText(s);
    className("android.widget.Button").findOne().click();
    sleep(commonModule.random(1000, 2000));
    //点击输入X坐标
    this.press(630, 140, 15);
    sleep(commonModule.random(2000, 3000));
    setText(x);
    className("android.widget.Button").findOne().click();
    sleep(commonModule.random(1000, 2000));
    this.press(790, 140, 15);
    sleep(commonModule.random(2000, 3000));
    setText(y);
    className("android.widget.Button").findOne().click();
    sleep(commonModule.random(1000, 2000));
    this.press(886, 144, 15);
    sleep(commonModule.random(8000, 10000));
};
command.snapshot = function () {
    var imgPath = "/sdcard/rok_stat/upload/" + new Date().getTime() + ".png";
    var cs = images.captureScreen(imgPath);
    var res = http.postMultipart(confModule.getUrl() + "common/upload", {
        file: open(imgPath)
    }, {
        headers: {
            'token': confModule.getToken()
        }
    });
    files.remove(imgPath);
};
command.extractUnion = function (unionId) {
    console.log("抓取联盟" + unionId + "数据开始")
    var union = http.get(confModule.getUrl() + "union/getUnion?id=" + unionId, {
        headers: {
            'token': confModule.getToken()
        }
    });
    var serverId;
    var coordinateX;
    var coordinateY;
    if (union.statusCode == 200) {
        var json = JSON.parse(union.body.string());
        if (json.code == "00000") {
            serverId = json.data.serverId;
            coordinateX = json.data.coordinateX;
            coordinateY = json.data.coordinateY;
        }
    }
    this.jumpCoordinate(serverId, coordinateX, coordinateY);
    // var nameRes = http.postJson(confModule.getUrl() + "stat/getFinishedNames", {
    //     "serverId": serverId,
    //     "unionId": unionId
    // },{
    //     headers: {
    //         'token': confModule.getToken()
    //     }
    // });
    var finishedNames = new Array();
    // if (nameRes.statusCode == 200) {
    //     var json = JSON.parse(nameRes.body.string());
    //     if (json.code == "00000") {
    //         finishedNames = json.data;
    //     }
    // }

    //点击盟堡
    var names = new Array();
    commandModule.press(635, 365, 10);

    var templ = images.read("/sdcard/rok_stat/xt.png");
    var p = findImage(captureScreen(), templ);
    if (p) {
        commandModule.press(p.x + 10, p.y + 10, 10);
    } else {
        return;
    }
    templ.recycle();
    commandModule.press(989, 575, 15);
    //R5
    commandModule.press(431, 146, 30);
    sleep(commonModule.random(1000, 1500));
    commandModule.press(574, 115, 15);
    sleep(commonModule.random(1000, 1500));
    commandModule.extract(serverId, unionId, names, finishedNames, 0, 0);
    // //R4
    commandModule.press(1105, 255, 5);//关闭R4
    var unionMember = commonModule.unionMember();
    console.log("联盟人数", unionMember)
    if (unionMember[0] > 0) {
        names = [];
        commandModule.press(1105, 255, 5);//打开R4
        for (var h = 0; h < Math.ceil(unionMember[0] / 4); h++) {
            for (var l = 0; l < 4; l++) {
                if (names.length != unionMember[0]) {
                    commandModule.press(215 + (l * 240), 350 + (h * 130), 5);
                    commonModule.waitColorVisible(400 + (l * 240), 320 + (h * 130), "#00C2FF")
                    commandModule.press(355 + (l * 240), 320 + (h * 130), 5);
                    commonModule.waitColorVisible(1120, 100, "#B6B3A6")
                    commandModule.extract(serverId, unionId, names, finishedNames, 0, 0);
                }
            }
        }
        commandModule.press(1105, 255, 5);//关闭R4
    }
    if (unionMember[1] > 0) {
        commandModule.press(1105, 330, 5);//展开R3
        commandModule.swipeUp(640, 325, 140);
        commandModule.unionMemberExtract(unionMember[1], serverId, unionId, finishedNames);
    }
    if (unionMember[2] > 0) {
        commandModule.press(989, 575, 15);
        commandModule.press(1105, 255, 5);//关闭R4
        commandModule.press(1105, 395, 5);//展开R2
        commandModule.swipeUp(640, 325, 210);
        commandModule.unionMemberExtract(unionMember[2], serverId, unionId, finishedNames);
    }
    if (unionMember[3] > 0) {
        commandModule.press(989, 575, 15);
        commandModule.press(1105, 255, 5);//关闭R4
        commandModule.press(1105, 472, 5);//展开R1
        commandModule.swipeUp(640, 325, 275);
        commandModule.unionMemberExtract(unionMember[3], serverId, unionId, finishedNames);
    }
    commandModule.press(1117, 43, 10);
    this.press(60, 650, 35);
    console.log("抓取联盟" + unionId + "数据完毕")
};
command.extract = function (serverId, unionId, array, finishedNames, x, y) {
    var clipBtn = commonModule.getClipBtn();
    if (!clipBtn) {
        var imgPath = "/sdcard/rok_stat/upload/" + new Date().getTime() + "_noClipBtn_" + x + "_" + y + ".png";
        images.captureScreen(imgPath);
        var res = http.postMultipart(confModule.getUrl() + "common/upload", {
            file: open(imgPath)
        }, {
            headers: {
                'token': confModule.getToken()
            }
        });
        files.remove(imgPath)
        return;
    }

    while (true) {
        if (!images.detectsColor(captureScreen(), "#00D0FF", clipBtn.x, 94, 16, "diff")) {
            this.press(clipBtn.x, clipBtn.y, 5);
        } else {
            break;
        }
        sleep(500)
    }
    this.press(clipBtn.x, 155, 5);
    var nickName = getClip();
    if (finishedNames.indexOf(nickName) != -1) {
        array.push(nickName);
        this.press(1088, 81, 10);
        return;
    }

    if (array.indexOf(nickName) == -1) {
        var gameId = commonModule.gameId();
        this.press(309, 529, 30);
        sleep(1000);
        var currentPower = commonModule.currentPower();
        var death = commonModule.death();
        this.press(863, 123, 5);
        var killCount = commonModule.killCount();
        http.postJson(confModule.getUrl() + "stat/addStat", {
            "serverId": serverId,
            "unionId": unionId,
            "gameId": gameId,
            "nickName": nickName,
            "currentPower": currentPower,
            "maxPower": death[0],
            "death": death[1],
            "t1Kill": killCount[0],
            "t2Kill": killCount[1],
            "t3Kill": killCount[2],
            "t4Kill": killCount[3],
            "t5Kill": killCount[4]
        }, {
            headers: {
                'token': confModule.getToken()
            }
        });
        array.push(nickName);
        this.press(1117, 43, 10);
    }
    this.press(1092, 81, 10);
}


command.unionMemberExtract = function (mCount, serverId, unionId, finishedNames) {
    var names = [];
    for (var page = 0; page < Math.ceil(mCount / 12); page++) {
        var points = [];
        commonModule.getPoints(620, points);
        commonModule.getPoints(880, points);
        for (var i = 0; i < points.length; i++) {
            var p = points[i];
            commandModule.press(p.x, p.y, 5);
            var infoBtn = commonModule.getPoint(p.x == 620 ? 520 : 1000);
            while (!infoBtn) {
                sleep(500)
                infoBtn = commonModule.getPoint(p.x == 620 ? 520 : 1000);
            }
            commandModule.press(p.x == 620 ? 520 : 1000, infoBtn.y + 10, 5);
            commonModule.waitColorVisible(1120, 100, "#B6B3A6")
            commandModule.extract(serverId, unionId, names, finishedNames, p.x == 620 ? 520 : 1000, infoBtn.y + 10);
        }
        var pointsHeight = images.findAllPointsForColor(captureScreen(), "#023C54", {
            region: [620, 220, 1, 460],
            threshold: 16
        })
        commandModule.swipeUp(640, 520, pointsHeight[pointsHeight.length - 1].y - 220);//468
    }
    commandModule.press(1117, 43, 10);
};
command.clickCancel = function () {
    var cs = captureScreen();
    var cancel = images.read("/sdcard/rok_stat/cancel.png");
    var cancelPoint = findImage(cs, cancel);
    if (cancelPoint) {
        this.press(cancelPoint.x, cancelPoint.y, 10);
        cancel.recycle();
        this.clickCancel();
        sleep(commonModule.random(500, 1000));
    } else {
        cancel.recycle();
        return;
    }
};

command.giveTitle = sync(function (serverId, title, coordinateX, coordinateY) {
    // launchApp("万国觉醒");
    this.clickCancel();
    while (commonModule.imgExistInRegion("/sdcard/rok_stat/qd.png", 580, 440, 120, 60)) {
        this.pressNoDelay(638, 472, 10);
        sleep(100)
    }
    if (commonModule.imgExistInRegion("/sdcard/rok_stat/yz.png", 600, 300, 400, 150)) {
        console.log("弹出验证");
    }
    if (!commonModule.isWord()) {
        this.press(60, 650, 35);
    }
    commonModule.waitColorVisible(67, 640, "#ECFFFF")
    //点击查找地址按钮
    this.press(330, 20, 10);
    sleep(500);
    var cs = captureScreen();
    var fdj = images.read("/sdcard/rok_stat/fdj.png");
    var fdjp = findImage(cs, fdj, {
        region: [850, 115, 70, 57]
    });
    while (!fdjp) {
        //点击查找地址按钮
        this.pressNoDelay(330, 20, 10);
        sleep(500);
        var cs2 = captureScreen();
        fdjp = findImage(cs2, fdj, {
            region: [850, 115, 70, 57]
        });
        cs2.recycle();
    }
    cs.recycle();
    fdj.recycle();
    //点击输入服务器编码
    this.pressNoDelay(455, 140, 15);
    var isWaitWord = (className("android.widget.EditText").findOne().text() != serverId.toString().toUpperCase())
    className("android.widget.EditText").findOne().setText(serverId);
    while (className("android.widget.EditText").findOne().text().toUpperCase()!=serverId.toString().toUpperCase()) {
        className("android.widget.EditText").findOne().setText(serverId);
        sleep(100)
    }
    className("android.widget.Button").findOne().click();
    //点击输入X坐标
    this.pressNoDelay(630, 140, 15);
    while (!className("android.widget.EditText").exists()) {
        this.pressNoDelay(630, 140, 15);
        sleep(100)
    }
    className("android.widget.EditText").findOne().setText(coordinateX);
    while (className("android.widget.EditText").findOne().text()=="") {
        className("android.widget.EditText").findOne().setText(coordinateX);
        sleep(100)
    }
    className("android.widget.Button").findOne().click();
    this.pressNoDelay(790, 140, 15);
    while (!className("android.widget.EditText").exists()) {
        this.pressNoDelay(790, 140, 15);
        sleep(100)
    }
    className("android.widget.EditText").findOne().setText(coordinateY);
    while (className("android.widget.EditText").findOne().text()=="") {
        className("android.widget.EditText").findOne().setText(coordinateY);
        sleep(100)
    }
    className("android.widget.Button").findOne().click();
    while (commonModule.imgExistInRegion("/sdcard/rok_stat/fdj.png", 850, 115, 70, 57)) {
        this.pressNoDelay(886, 144, 15);
        sleep(100)
    }
    if (isWaitWord) {
        console.log("切换地图等待10秒")
        sleep(10000)
    }
    //sleep(commonModule.random(5000, 6000));

    // var castle = commonModule.getCastle();
    // while(!castle){
    //     castle=commonModule.getCastle();
    // }
    // console.log("城堡坐标："+castle.x+","+castle.y);
    // var r = 50;
    // if (confModule.getServerId() == serverId) {
    //     r = 100;
    // }
    var templ = images.read("/sdcard/rok_stat/zyyz.png");
    var templ2 = images.read("/sdcard/rok_stat/title.png");
    var len = [640, 630, 650, 620, 660, 610, 670, 600, 680, 590, 690, 580, 700, 570, 710, 560, 720, 550, 730, 540, 740];
    for (var i = 0; i < len.length; i++) {
        this.pressNoDelay(len[i], 350, 5);
        sleep(500);
        var cs3 = captureScreen();
        if (!findImage(cs3, templ)&&!findImage(cs3, templ2, {
            threshold: 0.8
        })) {
            continue;
        }
        var p = commonModule.findImage("/sdcard/rok_stat/title.png");
        if (p) {
            this.pressNoDelay(p.x + 10, p.y + 10, 10);
            commonModule.waitImgVisibleInRegionClick("/sdcard/rok_stat/fg.png", 249, 138, 99, 73,p.x + 10, p.y + 10)
            commandModule.swipeUpWithDuration(638, 578, 520, 500)
            while (!commonModule.waitImgVisibleInRegionWithTimeOut("/sdcard/rok_stat/lg.png", 250, 280, 99, 76, 20)) {
                commandModule.swipeUpWithDuration(638, 578, 520, 500)
            }
            if (commonModule.imgExistInRegion("/sdcard/rok_stat/dj.png", 126, 69, 1021, 523)) {
                commonModule.waitImgVisibleInRegion("/sdcard/rok_stat/qd.png", 570, 615, 130, 45)
                this.pressNoDelay(640, 640, 10);
                sleep(500)
                while (commonModule.imgExistInRegion("/sdcard/rok_stat/qd.png", 570, 615, 130, 45)) {
                    this.pressNoDelay(640, 640, 10);
                }
            } else {
                commandModule.swipeDownWithDuration(638, 578, 520, 500)
                while (!commonModule.waitImgVisibleInRegionWithTimeOut("/sdcard/rok_stat/fg.png", 249, 138, 99, 73, 20)) {
                    commandModule.swipeDownWithDuration(638, 578, 520, 500)
                }
                //0:公爵 1:科学家 2:建筑师
                if (title == 0) {
                    if (!commonModule.imgExistInRegion("/sdcard/rok_stat/dj.png", 490, 365, 60, 60)) {
                        this.pressNoDelay(522, 395, 5);//公爵522 大建筑752 科学982
                    }
                } else if (title == 1) {
                    if (!commonModule.imgExistInRegion("/sdcard/rok_stat/dj.png", 950, 365, 60, 60)) {
                        this.pressNoDelay(982, 395, 5);//公爵522 大建筑752 科学982
                    }
                } else {
                    if (!commonModule.imgExistInRegion("/sdcard/rok_stat/dj.png", 720, 365, 60, 60)) {
                        this.pressNoDelay(752, 395, 5);//公爵522 大建筑752 科学982
                    }
                }
                commonModule.waitImgVisibleInRegion("/sdcard/rok_stat/qd.png", 570, 615, 130, 45)
                this.pressNoDelay(640, 640, 10);
                sleep(500)
                while (commonModule.imgExistInRegion("/sdcard/rok_stat/qd.png", 570, 615, 130, 45)) {
                    this.pressNoDelay(640, 640, 10);
                }
            }
            break

        }
    }
    templ.recycle();
});


command.dkpExtract = function () {
    launchApp("万国觉醒");
    this.clickCancel();
    while (!commonModule.isWord()) {
        this.press(60, 650, 35);
        sleep(commonModule.random(5000, 6000));
    }
    commandModule.pressNoDelay(48, 36, 10);
    commonModule.waitImgVisibleInRegion("/sdcard/rok_stat/rank.png", 385, 480, 120, 130)
    commandModule.pressNoDelay(443, 531, 10);
    commonModule.waitImgVisibleInRegion("/sdcard/rok_stat/personal_power.png", 155, 335, 115, 165)
    commandModule.pressNoDelay(210, 403, 10);
    commonModule.waitImgVisibleInRegion("/sdcard/rok_stat/personal_power_rank.png", 540, 18, 210, 50)
    var nameRes = http.get(confModule.getUrl() + "stat/getFinishedNames?serverId=" + confModule.getDkpServerId(), {
        headers: {
            'token': confModule.getToken()
        }
    });
    var finishedNames = new Array();
    if (nameRes.statusCode == 200) {
        var json = JSON.parse(nameRes.body.string());
        if (json.code == "00000") {
            finishedNames = json.data;
        }
    }
    console.log(finishedNames)
    var perName = "";
    var ys = [225, 305, 385];
    for (var i = 0; i < ys.length; i++) {
        if (confModule.getDkpTaskStatus() == 0) {
            return;
        }
        this.pressNoDelay(630, ys[i], 10);
        var cpName = this.extractOne(finishedNames, perName);
        perName = cpName;
    }
    var cpNames = [];
    for (var i = 4; i < 999; i++) {
        if (confModule.getDkpTaskStatus() == 0) {
            return;
        }
        this.pressNoDelay(630, 465, 10);
        var c1 = commonModule.waitImgVisibleInRegionTimeOut("/sdcard/rok_stat/achievement.png", 655, 480, 110, 130)
        if (!c1) {
            this.pressNoDelay(630, 545, 10);
            var c2 = commonModule.waitImgVisibleInRegionTimeOut("/sdcard/rok_stat/achievement.png", 655, 480, 110, 130)
            if (!c2) {
                this.pressNoDelay(630, 625, 10);
                var c3 = commonModule.waitImgVisibleInRegionTimeOut("/sdcard/rok_stat/achievement.png", 655, 480, 110, 130)
                if (!c3) {
                    console.log("连续3次点击失败")
                    commandModule.swipeUp(630, 465, 50);
                    this.pressNoDelay(630, 625, 10);
                    var c4 = commonModule.waitImgVisibleInRegionTimeOut("/sdcard/rok_stat/achievement.png", 655, 480, 110, 130)
                    if (!c4) {
                        console.log("连续4次点击失败")
                    }
                }
            }
        }
        if (i <= finishedNames.length) {
            sleep(500)
            this.pressNoDelay(1092, 81, 10);//关闭个人信息主页
            commonModule.waitImgVisibleInRegionClick("/sdcard/rok_stat/personal_power_rank.png", 540, 18, 210, 50, 1211, 351)
            sleep(500)
            if (commonModule.imgExistInRegion("/sdcard/rok_stat/personal_power.png", 155, 335, 115, 165)) {
                commandModule.pressNoDelay(210, 403, 10);
                i = 4
            }
        } else {
            var cpName = this.extractOne(finishedNames, perName);
            perName = cpName
            cpNames.push(cpName)
            if (cpNames.length > 4) {
                if (cpNames[0] == cpName) {
                    break
                } else {
                    cpNames = []
                }
            }
        }
    }
    var ys2 = [545, 625];
    for (var i = 0; i < ys2.length; i++) {
        if (confModule.getDkpTaskStatus() == 0) {
            return;
        }
        this.pressNoDelay(630, ys2[i], 10);
        var cpName = this.extractOne(finishedNames, perName);
        perName = cpName
    }
    sleep(500);
    this.pressNoDelay(1117, 43, 10);
    commonModule.waitImgVisibleInRegion("/sdcard/rok_stat/personal_power.png", 155, 335, 115, 165)
    this.pressNoDelay(1117, 43, 10);
    commonModule.waitImgVisibleInRegion("/sdcard/rok_stat/rank.png", 385, 480, 120, 130)
    this.pressNoDelay(1092, 81, 10);

};

command.extractOne = function (finishedNames, perName) {
    var fzp = commonModule.waitImgVisibleInRegionTimeOut("/sdcard/rok_stat/fz.png", 530, 210, 340, 35)
    if (!fzp) {
        this.pressNoDelay(1092, 81, 10);//关闭个人信息主页
        commonModule.waitImgVisibleInRegionClick("/sdcard/rok_stat/personal_power_rank.png", 540, 18, 210, 50, 1211, 351)
        sleep(500)
        if (commonModule.imgExistInRegion("/sdcard/rok_stat/personal_power.png", 155, 335, 115, 165)) {
            commandModule.pressNoDelay(210, 403, 10);
        }
        return perName
    }
    commonModule.waitImgVisibleInRegion("/sdcard/rok_stat/achievement.png", 655, 480, 110, 130)
    commonModule.waitColorVisible(603, 203, "#1B97CF")
    var gameId = commonModule.gameId();

    for (var i = 0; i < 3; i++) {
        this.pressNoDelay(fzp.x + 10, 231, 0);
        commonModule.waitImgVisibleInRegionClick("/sdcard/rok_stat/copy_nickname.png", 500, 130, 365, 60, fzp.x + 10, 231)
        this.pressNoDelay(fzp.x + 10, 157, 10);
        sleep(500);
        var nickName = getClip();
        sleep(500);
        if (nickName != perName) {
            break
        }
    }
    if (finishedNames.indexOf(nickName) == -1) {
        this.pressNoDelay(309, 529, 30);//点击更多信息
        commonModule.waitImgVisibleInRegionClick("/sdcard/rok_stat/more_info.png", 550, 20, 190, 50, 309, 529)
        commonModule.waitColorVisible(640, 125, "#1C99CF")
        var currentPower = commonModule.currentPower();
        var death = commonModule.death();
        this.pressNoDelay(863, 123, 5);
        commonModule.waitColorVisible(1037, 266, "#B4883B")
        var killCount = commonModule.killCount();
        http.postJson(confModule.getUrl() + "stat/addStat", {
            "serverId": confModule.getDkpServerId(),
            "gameId": gameId,
            "nickname": nickName,
            "currentPower": currentPower,
            "maxPower": death[0],
            "death": death[1],
            "t1Kill": killCount[0],
            "t2Kill": killCount[1],
            "t3Kill": killCount[2],
            "t4Kill": killCount[3],
            "t5Kill": killCount[4]
        }, {
            headers: {
                'token': confModule.getToken()
            }
        });
        sleep(500);
        this.pressNoDelay(1117, 43, 10);
        commonModule.waitImgVisibleInRegion("/sdcard/rok_stat/achievement.png", 655, 480, 110, 130)

    }
    commonModule.waitImgVisibleInRegion("/sdcard/rok_stat/personal_info.png", 535, 60, 235, 45)
    sleep(500)
    this.pressNoDelay(1092, 81, 10);//关闭个人信息主页
    commonModule.waitImgVisibleInRegionClick("/sdcard/rok_stat/personal_power_rank.png", 540, 18, 210, 50, 1211, 351)
    sleep(500)
    if (commonModule.imgExistInRegion("/sdcard/rok_stat/personal_power.png", 155, 335, 115, 165)) {
        commandModule.pressNoDelay(210, 403, 10);
    }
    sleep(500)
    return nickName
}

module.exports = command;